#include <cstdio>
#include <cstring>

#include <algorithm>

using namespace std;

int n, m;
char A[2000005];
char B[1000005], BB[1000005];

int lcp[2000005], reversed_lcp[2000005];
int lcpB[1000005];

int minRepresentation(char S[], int len)
{
	int p1 = 0, p2 = 1;

	while( p2 < len ) {
		int offset = 0;

		while( offset < n && S[(p1+offset) % len] == S[(p2+offset) % len] )
			++offset;
		if( offset == n ) break;

		if( S[(p1+offset) % len] < S[(p2+offset) % len] )
			p2 += offset+1;
		else {
			p1 = p2;
			++p2;
		}
	}

	return p1;
}

void doMatch( char A[], int lenA, char B[], int lenB, int lcp[] )
{
	int k = 0;

	lcpB[0] = 0;
	for( int i = 1; i < lenB; ++i ) {
		if( k+lcpB[k]-1 >= i ) {
			int match = lcpB[i-k];

			if( i+match < k+lcpB[k] ) lcpB[i] = match;
			else {
				lcpB[i] = k+lcpB[k]-i;
				while( i + lcpB[i] < lenB && B[i + lcpB[i]] == B[lcpB[i]] ) 
					++lcpB[i];
			}
		} else {
			lcpB[i] = 0;
			while( i + lcpB[i] < lenB && B[i + lcpB[i]] == B[lcpB[i]] ) 
				++lcpB[i];
		}
		if( i + lcpB[i] > k + lcpB[k] ) 
			k = i;
	}

	k = 0;

	lcp[0] = 0;
	while( lcp[0] < lenB && A[lcp[0]] == B[lcp[0]] )
		++lcp[0];

	for( int i = 1; i < lenA; ++i ) {

		if( k+lcp[k]-1 >= i ) {
			int match = lcpB[i-k];

			if( i+match < k+lcp[k] ) lcp[i] = match;
			else {
				lcp[i] = k+lcp[k]-i;
				while( i + lcp[i] < lenA && lcp[i] < lenB && A[i + lcp[i]] == B[lcp[i]] ) 
					++lcp[i];
			}
		} else {
			lcp[i] = 0;
			while( i + lcp[i] < lenA && lcp[i] < lenB && A[i + lcp[i]] == B[lcp[i]] ) {
				++lcp[i];
			}
		}
		if( i + lcp[i] > k + lcp[k] ) 
			k = i;
	}
}

int main( void )
{
	freopen( "input.txt", "r", stdin );

	scanf( "%d %d", &n, &m );
	gets( A );
	gets( A );
	gets( B );

	for( int i = 0; i < n; ++i )
		A[i+n] = A[i];

	int startPos = minRepresentation(B, m);

	for( int i = 0; i < m; ++i ) BB[i] = B[(startPos+i) % m];
	for( int i = 0; i < m; ++i ) B[i] = BB[i];

	doMatch(A, n*2, B, m, lcp);

	reverse(A, A + n*2);
	reverse(B, B + m);
	doMatch(A, n*2, B, m, reversed_lcp);

	reverse(reversed_lcp, reversed_lcp + n*2);
	reverse(A, A + n*2);

	int best = -1;
	int bestShift = -1;

	for( int i = 0; i < n; ++i ) {
		if( lcp[i] + reversed_lcp[i+m-1] + 1 >= m ) {
			int shift = min(i, n-i);

			if( best < 0 || bestShift > shift ) best = i, bestShift = shift;
		}

//		if( i == 2 ) printf( "lcp[i] = %d, reversed_lcp[i+m-1] = %d\n", lcp[i], reversed_lcp[i+m-1] );
	}

	for( int i = 0; i < m; ++i ) putchar( BB[i] );
	putchar( '\n' );
	for( int i = 0; i < n; ++i ) putchar( A[(i+best)%n] );
	putchar( '\n' );

	return 0;
}
